import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import { HashRouter as Router, Route, Switch, Redirect } from 'react-router-dom'
import createHistory from 'history/createHashHistory'
import { observer, Provider} from 'mobx-react'
import {useStrict} from 'mobx'
import store from './stores/store'
import shopStore from './stores/shopStore'
import storeItemStore from './stores/storeItemStore'
import itemStore from './stores/itemStore'
import itemFilterStore from './stores/itemFilterStore'
import classifyStore from './stores/classifyStore'
import recordStore from './stores/recordStore'
import salesStore from './stores/salesStore'
import userStore from './stores/userStore'
import logStore from './stores/logStore'
import homeStore from './stores/homeStore'
import './index.css'
import App from './App'
import Login from './components/Login/Login'
import axios from 'axios'
import { Modal } from 'antd'
const history = createHistory()
//const store = new state()
const stores = {
    store,
    shopStore,
    storeItemStore,
    itemStore,
    itemFilterStore,
    classifyStore,
    recordStore,
    salesStore,
    userStore,
    logStore,
    homeStore
}

useStrict(true)

axios.defaults.timeout = 10000

axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    console.log()
    console.log('拦截器request...', config)
    const session = JSON.parse(window.localStorage.getItem("riderMain"))
    if (session) {
        const token = session.AccessToken
        config.headers['X-Auth-Token'] = token
    }
    return config
}, function (error) {
    // Do something with request error
    return Promise.reject(error)
})

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    console.log('拦截器response...', response)
    if (response.status === 200) {
        const token = response.data.status//response.data.? //headers['X-Auth-Token']
        //剔除login的请求
        if (response.config.url.indexOf("/api/auth") === -1) {
            if (token === 401 || token === 4003) { //!token
                Modal.warning({
                    title: '登录时效过期，请重新登录！',
                    onOk() {
                        window.localStorage.removeItem("riderMain")
                        window.location.hash = '#/login'
                    },
                })
            }
        }
    } else {
        Modal.warning({
            title: '网络异常！',
            onOk() {
                window.localStorage.removeItem("riderMain")
                window.location.hash = '#/login'
            },
        })
    }
    return response
}, function (error) {
    // Do something with response error
    return Promise.reject(error)
})

const redirect = props => <Redirect to={{ pathname: '/login', state: { from: props.location } }} />

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => {
        const session = JSON.parse(window.localStorage.getItem("riderMain"))
        if (session) {
            const user = session.UserId
            if (user && user !== "") { 
                    store.getUserInfo(user)
                return <Component {...props} />
            } else {
                return redirect(props)
            }
        } else {
            return redirect(props)
        }
    }} />)

@observer
export default class Index extends React.Component {
    static contextTypes = {
        store: PropTypes.object,
    }

    render() {
        return (
            <Provider {...stores}>
                <Router history={history}>
                    <Switch>
                        <Route exact={true} path="/login" component={Login} />
                        <PrivateRoute exact={false} path="/" component={App} />
                    </Switch>
                </Router>
            </Provider>
        )
    }
}
ReactDOM.render((
    <Index />
), document.getElementById('root'))
//registerServiceWorker()
